const db = require('@/db/db-connection')
const { newRandomId, multipleColumnSet } = require('@/utils/common.util')

class ResumeModel {
  async create (params) {
    const id = newRandomId()

    const { userId, content, themeColor, themeStyleName } = params

    const sql = 'INSERT INTO resume (id, userId, content, themeColor, themeStyleName) VALUES (?, ?, ?, ?, ?)'

    try {
      await db.query(sql, [id, userId, content, themeColor, themeStyleName])
    } catch (error) {
      throw new Error(error)
    }
  }

  async update (userId, params) {
    const { content, themeColor, themeStyleName } = params

    const sql = 'UPDATE resume SET content = ?, themeColor = ?, themeStyleName = ? WHERE userId = ?'

    try {
      await db.query(sql, [content, themeColor, themeStyleName, userId])
    } catch (error) {
      throw new Error(error)
    }
  }

  async findOne (params) {
    const { columnSet, values } = multipleColumnSet(params)

    const sql = `SELECT id FROM resume WHERE ${columnSet}`

    try {
      const data = await db.query(sql, values)

      return data[0]
    } catch (error) {
      throw new Error(error)
    }
  }

  async findOneByUserId (userId) {
    const sql = 'SELECT id, content, userId, themeColor, themeStyleName FROM resume WHERE userId = ?'

    try {
      const data = await db.query(sql, [userId])

      return data[0]
    } catch (error) {
      throw new Error(error)
    }
  }

  async findOneById (id) {
    const sql = 'SELECT id, content, userId, themeColor, themeStyleName FROM resume WHERE id = ?'

    try {
      const data = await db.query(sql, [id])

      return data[0]
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new ResumeModel()
